package jui.maps
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.TextEvent;
	
	import jui.business.InputManager;
	import jui.business.ManagersFactory;
	import jui.business.TextManager;
	
	import mx.binding.utils.BindingUtils;
 	
	public class TextEventMap extends EventDispatcher implements IJUIEventMap
	{
		private var app: JUI;
		private var textManager: TextManager;
		private var inputManager: InputManager;
		
		public function setManagers(): void
		{
			//new TextManager();
			//inputManager = new InputManager();
			
			var gm: Function = ManagersFactory.getInstance().getManager;
			textManager = gm(TextManager.getQName());
			inputManager = gm(InputManager.getQName());
			
			BindingUtils.bindSetter(app.messagePane.messageInput.setInputMessageText, inputManager, "inputText");
		}
		/**
		 * Set text event handler(s)
		 */
		public function setHandlers(): void
		{
			// When text link is clicked:
			app.systemManager.addEventListener(TextEvent.LINK, textEventHandler);

			// When text link is parsed after click:
			textManager.addEventListener(TextEvent.TEXT_INPUT, textInputHandler);
		}
		
		private function textEventHandler(event:TextEvent): void
		{
			textManager.parseLink( event.text );
		}
		
		// Dependency injection: inputManager -> messageInput
		
		private function textInputHandler(event:TextEvent): void
		{
			inputManager.inputText = event.text;
			textManager.parseLink(event.text);
		}		

		//-----------------------------------------------------------------------------
		// Singleton implementation
		//-----------------------------------------------------------------------------
		public static var instance: TextEventMap;
		public function TextEventMap(target:IEventDispatcher=null, app: JUI=null): void
 		{
			if(instance) throw new Error("TextEventMap is singleton");
			this.app = app;
			setManagers();
			setHandlers();
 		}
	}
}